package marvin.webapp.shopping.xml;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import marvin.webapp.exception.MarvinException;
import marvin.webapp.shopping.model.Item;
import marvin.webapp.shopping.model.ShoppingList;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ShoppingListXMLWriter {

	public static final String ROOT_NODE_NAME = "ShoppingList";
	public static final String ITEMS_NODE_NAME = "Items";
	public static final String ITEM_NODE_NAME = "item";
	
	public static final String CREATED_AT_ATTRIBUTE_NAME = "createdAt";
	public static final String NAME_ATTRIBUTE_NAME = "name";
	public static final String QUANTITY_ATTRIBUTE_NAME = "quantity";
	public static final String TICKED_ATTRIBUTE_NAME = "ticked";
	
	public ShoppingListXMLWriter() {
	}

	public void generate(ShoppingList list, String filePath) throws MarvinException {
		try {
			DocumentBuilderFactory docFactory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder;

			docBuilder = docFactory.newDocumentBuilder();
			
			// create List element
			Document doc = docBuilder.newDocument();
			Element rootElement = doc.createElement(ROOT_NODE_NAME);
			// set creation date
			rootElement.setAttribute(CREATED_AT_ATTRIBUTE_NAME, list.getCreationDate());
			doc.appendChild(rootElement);

			// Items elements
			Element items = doc.createElement(ITEMS_NODE_NAME);
			rootElement.appendChild(items);

			for (Item item : list.getItems()) {
				addItem(doc, items, item.getName(), item.getQuantity(), item.isTicked());
			}
			
			
			
			writeFile(doc, filePath);
		} catch (Exception e) {
			throw new MarvinException(
					"An error has occured when trying to generate XML file", e);
		}		
	}

	/**
	 * Write the content into xml file
	 * @param doc
	 * @param filePath
	 * @throws TransformerException
	 */
	private void writeFile(Document doc, String filePath) throws TransformerException {
		TransformerFactory transformerFactory = TransformerFactory
				.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(filePath));

		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
		
		transformer.transform(source, result);
	}

	private void addItem(Document doc, Element itemsNode, String itemName, int quantity, boolean ticked){
		Element item = doc.createElement(ITEM_NODE_NAME);
		item.setAttribute(NAME_ATTRIBUTE_NAME, itemName);
		item.setAttribute(QUANTITY_ATTRIBUTE_NAME, ""+quantity);
		item.setAttribute(TICKED_ATTRIBUTE_NAME, Boolean.valueOf(ticked).toString());
		itemsNode.appendChild(item);
	}
	
	public static void main(String argv[]) {
		try {
			ShoppingListXMLWriter wr = new ShoppingListXMLWriter();
			
			ShoppingList list = new ShoppingList();
			Item dentifrice = new Item();
			dentifrice.setName("Dentifrice");
			dentifrice.setQuantity(1);
			dentifrice.setTicked(false);
			list.addItem(dentifrice);
			
			
			wr.generate(list, "dummyList.xml");
			System.out.println("File saved!");

		} catch (MarvinException e) {
			e.printStackTrace();
		}
	}
}
